﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Xml.Linq;
using Kojarskiy.Core;
using Kojarskiy.Models;
using Mvc.Mailer;
using SiteMap = Kojarskiy.Models.SiteMap;

namespace Kojarskiy.Controllers
{
    public class HomeController : Controller
    {
        private KojarskiyDbEntities context = new KojarskiyDbEntities();

        public ActionResult Index(string language)
        {
            try
            {
                SiteMap siteMap;
                if (!string.IsNullOrEmpty(language))
                {
                    if (language.ToLower() != "ru" && language.ToLower() != "ua" && language.ToLower() != "en" && language.ToLower() != "de") language = "ru";
                    if (language != Localization.Current) Localization.Current = language;
                    siteMap = context.SiteMap.FirstOrDefault(x => x.ParentId == null && x.Culture == language);
                }
                else
                {
                    siteMap = context.SiteMap.FirstOrDefault(x => x.ParentId == null && x.Culture == Localization.Current);
                }

                if (siteMap != null)
                {
                    ViewBag.Title = siteMap.Title;
                    ViewBag.Description = siteMap.Description;
                    ViewBag.Keywords = siteMap.Keywords;

                    return View(siteMap);
                }
                return View("Exception");
            }
            catch (Exception ex)
            {
                return View("Exception");
            }
        }
        public ActionResult ChangeLanguage(string language, string returnUrl)
        {
            if (language != Localization.Current)
            {
                if (!string.IsNullOrEmpty(language) && language != Localization.Current)
                {
                    switch (language)
                    {
                        case "ru":
                            break;
                        case "en":
                            break;
                        case "de":
                            break;
                        case "ua":
                            break;
                    }
                    Localization.Current = language;
                }
            }
            Response.Redirect("~/"+ language);
            return null;
        }
        public ActionResult Page(string page, string language)
        {
            try
            {
                SiteMap siteMap;
                if (!string.IsNullOrEmpty(language))
                {
                    if(language != Localization.Current) Localization.Current = language.ToLower();
                    siteMap = context.SiteMap.First(x => x.Path == page && x.Culture == language);
                }
                else
                {
                    siteMap = context.SiteMap.First(x => x.Path == page && x.Culture == Localization.Current);
                }
                
                var block = context.Blocks.FirstOrDefault(x => x.SiteMapId == siteMap.SiteMapId);

                if (block != null)
                {
                    ViewData["PageBlocks"] = block.Layout;
                }

                ViewBag.Title = siteMap.Title;
                ViewBag.Description = siteMap.Description;
                ViewBag.Keywords = siteMap.Keywords;
                if(siteMap != null) return View(siteMap);
                return View("Exception");
            }
            catch (Exception ex)
            {
                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
                return View("Exception");
            }
        }

        public ActionResult Question(string page, string language)
        {
            try
            {
                var siteMap = context.SiteMap.First(x => x.Path == page && x.Culture == Localization.Current);
                var block = context.Blocks.FirstOrDefault(x => x.SiteMapId == siteMap.SiteMapId);

                if (block != null)
                {
                    ViewData["PageBlocks"] = block.Layout;
                }

                ViewBag.Title = siteMap.Title;
                ViewBag.Description = siteMap.Description;
                ViewBag.Keywords = siteMap.Keywords;

                if (siteMap != null) return View(siteMap);
                return View("Exception");
            }
            catch (Exception ex)
            {
                KojarskiyApplication.Log(KojarskiyApplication.ErrorType.Fatal, ex.Message, ex.StackTrace);
                return View("Exception");
            }
            
        }


        [HttpPost]
        public ActionResult Question(int SiteMapId, string ServiceType, string ClientName, string Address, string Phone, string Email, string Request)
        {
            try
            {
                var mailer = new MailSender();
                MvcMailMessage message = mailer.MailMessage(ServiceType, ClientName, Address, Phone, Email, Request);
                message.Send(SettingsManager.GetSmtpClient());
            }
            catch(Exception ex) 
            {
                KojarskiyApplication.Message = new Message(MessageType.Error, "Не удалось отправить запрос!");
            }
            var siteMap = context.SiteMap.First(x => x.SiteMapId == SiteMapId && x.Culture == Localization.Current);
            var block = context.Blocks.FirstOrDefault(x => x.SiteMapId == siteMap.SiteMapId);
            if (block != null)
            {
                ViewData["PageBlocks"] = block.Layout;
            }

            ViewBag.Title = siteMap.Title;
            ViewBag.Description = siteMap.Description;
            ViewBag.Keywords = siteMap.Keywords;

            KojarskiyApplication.Message = new Message(MessageType.Success, "Благодарим за Ваш запрос. Информация о стоимости наших услуг по данному запросу будет направлена Вам в течение двух рабочих дней.");
            if (siteMap != null) return View(siteMap);
            return View("Exception");
        }
        public ActionResult Search(string searchString)
        {
            var pages = SearchHelper.FindPages(searchString, context);
            var news = SearchHelper.FindNews(searchString, context);
            ViewBag.SearchString = searchString;
            ViewData["NewsSearchResult"] = news;
            return View(pages);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadImageFromEditor(HttpPostedFileBase upload, string CKEditorFuncNum, string CKEditor, string langCode)
        {
            string url;
            var fileId = Convert.ToInt32(DateTime.Now.ToString("MMddHHmmss"));
            var thumbpath = "";
            var path = FileHelper.UploadPhoto(upload, "ContentImages", fileId, out thumbpath, false);
            url = Url.Content(path);
            string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction(" +
                CKEditorFuncNum + ", \"" + url + "\", \"\");</script></body></html>";
            return Content(output);
        }

        public ActionResult SiteMap()
        {

            XNamespace ns = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9");
            XElement urlset = null;
            var siteMapDocument = new XDocument(urlset = new XElement(ns + "urlset"));

            urlset.Add(new XElement
            (ns + "url",
            new XElement(ns + "loc", "http://kojarskiy.com.ua/"),
            new XElement(ns + "lastmod", DateTime.Now),
            new XElement(ns + "changefreq", "daily"),
            new XElement(ns + "priority", "0.8")
            ));

            foreach (var links in context.SiteMap)
            {
                if (links.Path != "/")
                {
                    urlset.Add(new XElement
                    (ns + "url",
                    new XElement(ns + "loc", "http://kojarskiy.com.ua/" + links.Culture + "/Home/Page?page=" + links.Path),
                    new XElement(ns + "lastmod", DateTime.Now),
                    new XElement(ns + "changefreq", "daily"),
                    new XElement(ns + "priority", "0.2")
                    ));
                }
                else
                {
                    urlset.Add(new XElement
                    (ns + "url",
                    new XElement(ns + "loc", "http://kojarskiy.com.ua/" + links.Culture + "/"),
                    new XElement(ns + "lastmod", DateTime.Now),
                    new XElement(ns + "changefreq", "daily"),
                    new XElement(ns + "priority", "0.2")
                    ));                    
                }
            }

            foreach (var links in context.News)
            {
                urlset.Add(new XElement
                (ns + "url",
                new XElement(ns + "loc", "http://kojarskiy.com.ua/ru/News/Details/" + links.NewsId),
                new XElement(ns + "lastmod", DateTime.Now),
                new XElement(ns + "changefreq", "daily"),
                new XElement(ns + "priority", "0.2")
                ));
            }

            Response.Clear();
            Response.ContentType = "text/xml";
            Response.AddHeader("Content-Disposition", "attachment; filename=sitemap.xml");
            siteMapDocument.Save(Response.OutputStream);
            return Content(String.Empty);
        }
    }
}
